package com.kye.express.business.comment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.kye.express.R;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.IView;
import com.kye.express.databinding.ActivityCommentListBinding;
import com.kye.express.utils.EncryptionAESUtils;
import com.kye.express.view.ToastManager;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.comment.mine.CommentMineItemBean;
import com.kye.model.bean.comment.mine.RequestCommentMineList;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.CommentDataSource;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public interface CommentContract {

    interface CommentView extends IView {

        ActivityCommentListBinding getDataBinding();

        void refreshFirstSuccess(List<CommentMineItemBean> notificationList);

        void refreshFirstFailed(Throwable e);

        void refreshSuccess(List<CommentMineItemBean> notificationList);

        void refreshFailed(Throwable e);

        void loadMoreSuccess(List<CommentMineItemBean> notificationList);

        void loadMoreFailed(Throwable e);

        Context getContext();

        void quit();
    }

    class CommentPresenter extends BasePresenter<CommentView> {

        private CommentDataSource commentDataSource;
        private PageInfo pageInfo;
        private Observable<User> userObservable;
        private Disposable userDisposable;
        private User userInfo;

        public CommentPresenter() {
            commentDataSource = new CommentDataSource();
            pageInfo = new PageInfo();
        }

        @Override
        public void bind(CommentView view) {
            super.bind(view);
            userObservable = UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().<User>bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io());
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            if (savedInstanceState != null) {
                pageInfo = savedInstanceState.getParcelable(PageInfo.TAG_PAGE_INFO);
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            if (outState != null) {
                outState.putParcelable(PageInfo.TAG_PAGE_INFO, pageInfo);
            }
        }

        public void getuserInfo() {
            userObservable
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<User>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            userDisposable = d;
                        }

                        @Override
                        public void onNext(User user) {
                            userInfo = user;
                            if (user.isLogin()) {
                                refreshFirst();
                            } else {
                                /**
                                 * 未登录显示
                                 */
                                getView().getDataBinding().statusLayout.showErrorServerView();
                            }
                            if (!userDisposable.isDisposed()) {
                                userDisposable.dispose();
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

        public RequestCommentMineList getRequestParamSingle() {
            RequestCommentMineList requestCommentMineList = new RequestCommentMineList();
            String encryptPhone = null;
            try {
                encryptPhone = EncryptionAESUtils.Encrypt(userInfo.getPhone(), getView().getContext().getResources().getString(R.string.aes_password));
            } catch (Exception e) {
                /**
                 * 账号错误,退出
                 */
                e.printStackTrace();
                ToastManager.show(getView().getContext(), "账号错误!");
                Observable.timer(2, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) throws Exception {
                                getView().quit();
                            }
                        });
                return null;
            }
            requestCommentMineList.setCreateuser(encryptPhone);

            return requestCommentMineList;
        }

        public void refreshFirst() {
            RequestCommentMineList requestCommentMineList = getRequestParamSingle();
            if (requestCommentMineList == null) {
                return;
            }
            requestCommentMineList.setPageNum(String.valueOf(PageInfo.INDEX_DEFAULT));
            requestCommentMineList.setPageSize(String.valueOf(pageInfo.getPageSize()));
            commentDataSource.getMyCommentList(requestCommentMineList)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<List<CommentMineItemBean>>() {


                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<List<CommentMineItemBean>> result, List<CommentMineItemBean> commentMineItemBeans) {
                            pageInfo.resetPage();
                            getView().refreshFirstSuccess(result.getData());
                        }

                        @Override
                        public void onApiError(OpenApiResult<List<CommentMineItemBean>> result, int code, String msg) {

                        }

                        @Override
                        public void onLoaded() {

                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshFirstFailed(new RuntimeException(e));

                        }
                    });
        }

        public void refresh() {
            RequestCommentMineList requestCommentMineList = getRequestParamSingle();
            if (requestCommentMineList == null) {
                return;
            }
            requestCommentMineList.setPageNum(String.valueOf(PageInfo.INDEX_DEFAULT));
            requestCommentMineList.setPageSize(String.valueOf(pageInfo.getPageSize()));
            commentDataSource.getMyCommentList(requestCommentMineList)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<List<CommentMineItemBean>>() {


                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<List<CommentMineItemBean>> result, List<CommentMineItemBean> commentMineItemBeans) {
                            pageInfo.resetPage();
                            getView().refreshSuccess(result.getData());
                        }

                        @Override
                        public void onApiError(OpenApiResult<List<CommentMineItemBean>> result, int code, String msg) {
                            getView().refreshFailed(new RuntimeException(msg));
                        }

                        @Override
                        public void onLoaded() {

                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshFailed(new RuntimeException(e));
                        }
                    });
        }

        public void loadmore() {
            RequestCommentMineList requestCommentMineList = getRequestParamSingle();
            if (requestCommentMineList == null) {
                return;
            }
            requestCommentMineList.setPageNum(String.valueOf(pageInfo.getPageIndex() + 1));
            requestCommentMineList.setPageSize(String.valueOf(pageInfo.getPageSize()));
            commentDataSource.getMyCommentList(requestCommentMineList)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<List<CommentMineItemBean>>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<List<CommentMineItemBean>> result, List<CommentMineItemBean> commentMineItemBeans) {
                            pageInfo.increasePage();
                            getView().loadMoreSuccess(result.getData());
                        }

                        @Override
                        public void onApiError(OpenApiResult<List<CommentMineItemBean>> result, int code, String msg) {
                            getView().loadMoreFailed(new RuntimeException(msg));
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().loadMoreFailed(new RuntimeException(e));
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        public Observable<User> getUserObservable() {
            return userObservable;
        }

    }

}
